﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TcpLabCommon;

namespace Common.GeneralClass
{
    public class BlackBoxDB
    {
        public long blackAcqId;
        public string acqId;
        public string acqName;
        public CurrentDataPacketAndFFTData dataPaket;
        public DateTime insertTime;
        public int projectId;
        public int blackChannelId;
        public string cardId;
        public string channelId;
        public string fieldName;
        public float warningYellowLine;
        public float alarmRedline;
        public float dangerValue;
        public float dangerState;

    }

    public class OperateBlackBoxDB 
    {
        //MyDb mydb = Mdl_Class.Mydb;
        //MyDb mydb_insert = Mdl_Class.InsertMydb;
        //MyDb mydb_other = Mdl_Class.Mydb_other;

        //插入黑匣子数据
        public long AddBlackBoxData_ACQ(string tableName,BlackBoxDB bbdb)
        {
            long i = 0;
            using (MyDb mydb_insert = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {
                    mydb_insert.Open();
                    byte[] b = Activator.CreateInstance<StructHelper>().Serialize(bbdb.dataPaket);
                    i = Convert.ToInt64(mydb_insert.ExecuteNonQuery_BlackBox(tableName, b, bbdb));
                    mydb_insert.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("AddBlackBoxData_ACQ(string tableName,BlackBoxDB bbdb)", ex.ToString());
                }
            }
            return i;
        }


        //添加黑匣子数据明细
        public int AddBlackBoxData_Channel(BlackBoxDB bbdb)
        {
            int i = 0;
            using (MyDb mydb_insert = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {

                    mydb_insert.Open();
                    string sql = string.Format("insert into T_B_ACQ_BlackBox_Channel(blackAcqId,cardId,channelId,fieldName,warningYellowLine,alarmRedline,dangerValue,dangerState) values({0},'{1}','{2}','{3}',{4},{5},{6},{7}) Select @@Identity", bbdb.blackAcqId, bbdb.cardId, bbdb.channelId, bbdb.fieldName, bbdb.warningYellowLine, bbdb.alarmRedline, bbdb.dangerValue, bbdb.dangerState);

                    i = mydb_insert.ExecuteNonQuery(sql);
                    mydb_insert.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("AddBlackBoxData_Channel(BlackBoxDB bbdb)", ex.ToString());
                }
            }

            return i;
        }

        //删除黑匣子数据明细
        public int DelBlackBoxData_ACQ(DateTime dt_startTime)
        {
            int i = 0;
            using (MyDb mydb = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {

                    mydb.Open();
                    string sql = string.Format("delete from T_B_ACQ_BlackBox_ACQ where blackAcqId in (select top 1 blackAcqId from T_B_ACQ_BlackBox_ACQ where insertTime>='{0}')", dt_startTime);
                    i = mydb.ExecuteNonQuery(sql);
                    mydb.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("DelBlackBoxData_ACQ()", ex.ToString());
                }
            }

            return i;
        }


        //根据条件查询ACQ数据获取总数量
        public long GetAllACQErrPageSum(int prjid,string acqid,List<string>channelid,string dt1, string dt2)
        {
            //List<ACQDB> acqlist = new List<ACQDB>();
            long pagesum = 0;
            using (MyDb mydb = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {
                   
                    string sql = string.Format("select count(*) as pagecount from View_ACQ_Err where projectId={0} and acqId='{1}'", prjid, acqid);


                    if (channelid != null && channelid.Count>0)
                    {
                        int selectid = 0;
                        for (int i = 0; i < channelid.Count;i++ )
                        {
                            if (i == 0)
                            {
                                sql = sql + string.Format(" and ((cardId='{0}' and channelId='{1}')", channelid[i].Split(',')[0], channelid[i].Split(',')[1]);
                            }
                            else
                            {
                                sql = sql + string.Format(" or (cardId='{0}' and channelId='{1}')", channelid[i].Split(',')[0], channelid[i].Split(',')[1]);
                            }

                            selectid++;
                        }
                        sql = sql + ")";
                    }
                    if (dt1 != null&&dt1!="")
                    {
                        sql = sql + string.Format(" and insertTime between '{0}' and '{1}'", Convert.ToDateTime(dt1),  Convert.ToDateTime(dt2));
                    }
                    mydb.Open();
                    mydb.ExecuteReader(sql);
                    while (mydb.DataReader.Read())
                    {
                        pagesum = Convert.ToInt64(mydb.DataReader["pagecount"]); ;
                    }
         
                    mydb.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("GetAllACQErrPageSum(int prjid,string acqid,Dictionary<string,string>channelid,DateTime dt1, DateTime dt2)", ex.ToString());
                }
            }
            return pagesum;
        }



        //根据条件查询ACQ数据分页
        public List<BlackBoxDB> GetAllACQErrByPage(int prjid, string acqid, List<string> channelid, string dt1, string dt2, long pagevalue, long pagesize)
        {
            List<BlackBoxDB> acqlist = new List<BlackBoxDB>();

            using (MyDb mydb = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {
                    mydb.Open();
                    string sql = string.Format("select top {0} * from {1} where blackChannelId not in (select top {2} blackChannelId from {3}) and projectId={4} and acqId='{5}'", pagesize, "View_ACQ_Err", (pagevalue - 1) * pagesize, "View_ACQ_Err", prjid, acqid);


                    if (channelid != null && channelid.Count > 0)
                    {
                        int selectid = 0;
                        for (int i = 0; i < channelid.Count; i++)
                        {
                            if (i == 0)
                            {
                                sql = sql + string.Format(" and ((cardId='{0}' and channelId='{1}')", channelid[i].Split(',')[0], channelid[i].Split(',')[1]);
                            }
                            else
                            {
                                sql = sql + string.Format(" or (cardId='{0}' and channelId='{1}')", channelid[i].Split(',')[0], channelid[i].Split(',')[1]);
                            }

                            selectid++;
                        }
                        sql = sql + ")";
                    }
                    if (dt1 != null&&dt1!="")
                    {
                        sql = sql + string.Format(" and insertTime between '{0}' and '{1}'", Convert.ToDateTime(dt1), Convert.ToDateTime(dt2));
                    }
                    mydb.ExecuteReader(sql);
                    while (mydb.DataReader.Read())
                    {

                        BlackBoxDB acq = new BlackBoxDB();
                        acq.blackAcqId=Convert.ToInt64(mydb.DataReader["acqId"]);
           
                        acq.acqId = mydb.DataReader["acqId"].ToString();
                        acq.acqName = mydb.DataReader["acqName"].ToString();

                        byte[] by1 = mydb.DataReader["dataPaket"] as byte[];
                        CurrentDataPacketAndFFTData dpk = Activator.CreateInstance<StructHelper>().DeSerialize<CurrentDataPacketAndFFTData>(by1);
                        acq.dataPaket = dpk;
                        acq.insertTime = Convert.ToDateTime(mydb.DataReader["insertTime"]);
                        acq.projectId = Convert.ToInt32(mydb.DataReader["projectId"]);
                        acq.cardId=mydb.DataReader["CardId"].ToString();
                        acq.channelId=mydb.DataReader["ChannelId"].ToString();
                        acq.fieldName=mydb.DataReader["fieldName"].ToString();
                        acq.warningYellowLine=Convert.ToSingle(mydb.DataReader["warningYellowLine"]);
                        acq.alarmRedline=Convert.ToSingle(mydb.DataReader["alarmRedline"]);
                        acq.dangerValue=Convert.ToSingle(mydb.DataReader["dangerValue"]);
                        acq.dangerState=Convert.ToSingle(mydb.DataReader["dangerState"]);


                      
                        acqlist.Add(acq);
                    }

                    mydb.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("GetAllACQErrByPage(int prjid, string acqid, Dictionary<string, string> channelid, string dt1, string dt2)", ex.ToString());
                }
            }
            return acqlist;
        }


        /// <summary>
        /// 删除黑匣子数据库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DelBlackData(List<long> idlsit)
        {
            int delcount = 0;
            int delcount1 = 0;
            using (MyDb mydb_del = new MyDb(Mdl_Class.Systemset.DBConnectionString()))
            {
                try
                {
                    mydb_del.Open();
                    mydb_del.BeginTransaction();
                    string sql = string.Format("delete from T_B_ACQ_BlackBox_ACQ");
                    string sql1 = string.Format("delete from T_B_ACQ_BlackBox_Channel");
                    for (int i = 0; i < idlsit.Count; i++)
                    {
                        if (i > 1000)
                        {
                            delcount = mydb_del.ExecuteNonQuery(sql);
                            delcount1 = mydb_del.ExecuteNonQuery(sql1);
                            if (delcount >= 0 && delcount1 >= 0)
                            {
                                sql = string.Format("delete from T_B_ACQ_BlackBox_ACQ where blackAcqId={0}",idlsit[i]);
                                sql1 = string.Format("delete from T_B_ACQ_BlackBox_Channel where blackAcqId={0}",idlsit[i]);
                            }
                            else 
                            {
                                break;
                            }
                         
                        }
                        else
                        {
                            if (i == 0)
                            {
                                sql = sql + string.Format(" where blackAcqId={0}", idlsit[i]);
                                sql1 = sql1 + string.Format(" where blackAcqId={0}", idlsit[i]);
                            }
                            else
                            {
                                sql = sql + string.Format(" or blackAcqId={0}", idlsit[i]);
                                sql1 = sql1 + string.Format(" or blackAcqId={0}", idlsit[i]);
                            }
                        }

                    }
                    if (delcount >= 0 && delcount1 >= 0)
                    {
                        delcount = mydb_del.ExecuteNonQuery(sql);
                        delcount1 = mydb_del.ExecuteNonQuery(sql1);
                    }
                    if (delcount >= 0 && delcount1>=0)
                    {
                        mydb_del.Commit();
                    }
                    else
                    {
                        mydb_del.Rollback();
                    }

                    mydb_del.Close();
                }
                catch (Exception ex)
                {
                    Mdl_Class.WriteLog.dbErrLog("DelBlackData(List<int> idlsit)", ex.ToString());
                }
            }
            return delcount;
        }

    }
}
